package com.netty;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.netty.chat.service.ChatService;
import com.netty.common.module.ChatType;
import com.netty.serviceimpl.BananaService;
import com.system.util.PageData;
import com.system.util.Tools;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PongWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
import io.netty.util.CharsetUtil;

/**
 * 接收/处理/响应客户端websocket请求的核心业务处理类
 * @Function 
 * @Author zhaozhenhua
 * @Date 2018年5月28日
 */
@Service("myWebSocketHandler")
public class MyWebSocketHandler extends SimpleChannelInboundHandler<Object> {
	
	Gson gson = new Gson();
	
	@Resource(name = "chatService")
	private ChatService chatService;
	
	private static final Logger LOG = Logger.getLogger(MyWebSocketHandler.class.getName());
	
	
	// map用于channel和具体的用户名绑定起来，可以根据具体业务实现认证信息和channel绑定
    static final Map<String ,Channel> channelMap = Collections.synchronizedMap(new HashMap<String ,Channel>());
    //private static final ConcurrentHashMap<Long, Session> onlineSessions = new ConcurrentHashMap<>();
    // set保存登陆的用户信息
	static final List<String> set = new ArrayList<String>();
	
	private WebSocketServerHandshaker handshaker;
	private ChannelHandlerContext ctx;
	private String sessionId;
	
	private static final String WEB_SOCKET_URL = "ws://localhost:9090/websocket";

	//客户端与服务端创建连接的时候调用
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		NettyConfig.group.add(ctx.channel());
		System.out.println("客户端与服务端连接开启...");
	}

	//客户端与服务端断开连接的时候调用
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		NettyConfig.group.remove(ctx.channel());
		System.out.println("客户端与服务端连接关闭...");
	}

	//服务端接收客户端发送过来的数据结束之后调用
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
			ctx.flush();
	}

	//工程出现异常的时候调用
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
		System.out.println(sessionId + " 注销");
		BananaService.logout(sessionId); // 注销
		BananaService.notifyDownline(sessionId); // 通知有人下线
    }
	
	@Override
	public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
	System.out.println("WebSocket关闭");
	super.close(ctx, promise);
	System.out.println(sessionId + " 注销");
	//BananaService.logout(sessionId); // 注销
	//BananaService.notifyDownline(sessionId); // 通知有人下线
	}


	//服务端处理客户端websocket请求的核心方法
	@Override
	protected void messageReceived(ChannelHandlerContext context, Object msg) throws Exception {
		//处理客户端向服务端发起http握手请求的业务
		if (msg instanceof FullHttpRequest) {
			handHttpRequest(context,  (FullHttpRequest)msg);
		}else if (msg instanceof WebSocketFrame) { //处理websocket连接业务
			handWebsocketFrame(context, (WebSocketFrame)msg);
		}
	}
	
	/**
	 * 处理客户端与服务端之前的websocket业务
	 * @param ctx
	 * @param frame
	 */
	private void handWebsocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame){
		//判断是否是关闭websocket的指令
		if (frame instanceof CloseWebSocketFrame) {
			handshaker.close(ctx.channel(), (CloseWebSocketFrame)frame.retain());
		}
		//判断是否是ping消息
		if (frame instanceof PingWebSocketFrame) {
			ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
			return;
		}
		
		//判断是否是二进制消息，如果是二进制消息，抛出异常
		if( ! (frame instanceof TextWebSocketFrame) ){
			System.out.println("目前我们不支持二进制消息");
			throw new RuntimeException("【"+this.getClass().getName()+"】不支持消息");
		}
		//返回应答消息
		//获取客户端向服务端发送的消息
		String requestText = ((TextWebSocketFrame) frame).text();
		System.out.println("服务端收到客户端的消息====>>>" + requestText);
		//TextWebSocketFrame tws = new TextWebSocketFrame(new Date().toString() + ctx.channel().id() + " ===>>> " + requestText);
		//群发，服务端向每个连接上来的客户端群发消息
		//NettyConfig.group.writeAndFlush(tws);
		//chatService.publicChat("d6a3779de8204dfd9359403f54f7d27c", "245");
		
		
		String content = ((TextWebSocketFrame)frame).text();
		if(Tools.isEmpty(content)){
			System.out.println("conent客户端消息为空");
		}
		PageData CONTENT = gson.fromJson(content, PageData.class);
		if(CONTENT.getInterger("CHATTYPE")==ChatType.PUBLIC_CHAT){
			String HONOURUSER_ID = CONTENT.getString("HONOURUSER_ID");
			String msg = CONTENT.getString("CONTENT");
			chatService.publicChat(HONOURUSER_ID, msg);
		}if(CONTENT.getInterger("CHATTYPE")==ChatType.PRIVATE_CHAT){
			String HONOURUSER_ID = CONTENT.getString("HONOURUSER_ID");
			String msg = CONTENT.getString("CONTENT");
			String TARGETHONOURUSER_ID = CONTENT.getString("TARGETHONOURUSER_ID");
			chatService.privateChat(HONOURUSER_ID, TARGETHONOURUSER_ID,msg);
		}
		
	}
	
	
	
	
	/**
	 * 处理客户端向服务端发起http握手请求的业务
	 * @param ctx
	 * @param req
	 */
	private void handHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req){
		// 如果HTTP解码失败，返回HHTP异常
		if (!req.getDecoderResult().isSuccess() 
				|| ! ("websocket".equals(req.headers().get("Upgrade")))) {
			sendHttpResponse(ctx, req, 
					new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
			return;
		}
		// 正常WebSocket的Http连接请求，构造握手响应返回
		WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
				"ws://" + req.headers().get(HttpHeaders.Names.HOST), null, false);
		handshaker = wsFactory.newHandshaker(req);
		if (handshaker == null) {// 无法处理的websocket版本
			WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel());
		}else{// 向客户端发送websocket握手,完成握手
			handshaker.handshake(ctx.channel(), req);
			// 记录管道处理上下文，便于服务器推送数据到客户端
			this.ctx = ctx;
		}
	}
	
	/**
	 * 服务端向客户端响应消息
	 * @param ctx
	 * @param req
	 * @param res
	 */
	private void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req,
			DefaultFullHttpResponse res){
		// 返回应答给客户端
		if (res.getStatus().code() != 200) {
			ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
			res.content().writeBytes(buf);
			buf.release();
		}
		//服务端向客户端发送数据
		// 如果是非Keep-Alive，关闭连接
		ChannelFuture f = ctx.channel().writeAndFlush(res);
		if (!HttpHeaders.isKeepAlive(req)||res.getStatus().code() != 200) {
			f.addListener(ChannelFutureListener.CLOSE);
		}
	}
	
	
	/**
	* WebSocket返回
	* @param ctx
	* @param req
	* @param res
	*/
	public void sendWebSocket(String msg) throws Exception {
		if (this.handshaker == null || this.ctx == null || this.ctx.isRemoved()) {
		throw new Exception("尚未握手成功，无法向客户端发送WebSocket消息");
		}
		this.ctx.channel().write(new TextWebSocketFrame(msg));
		this.ctx.flush();
	}
}
